﻿using project.B12.IRepository.Base;
using project.B12.Model.Error;
using project.B12.Model.Models;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Documents;

namespace project.B12.Repository.Base
{
    public class SugarUnitOfWork : IUnitOfWork
    {
        //private readonly ISqlSugarClient _sqlSugarClient;
        private readonly SugarDbContext _dbContext;

        private int TranCount { get; set; }

        //private bool TranState { get; }

        public SugarUnitOfWork(SugarDbContext sugarDbContext)
        {
            _dbContext = sugarDbContext;
            //_dbContext.DB.Aop.OnLogExecuting = (s, p) =>
            //{
            //    //var a = UtilMethods.GetSqlString(DbType.SqlServer, s, p);
            //    //Console.WriteLine(s);
            //};
            _dbContext.DB.Aop.OnError = (exp) =>//SQL报错
            {
                //exp.sql 这样可以拿到错误SQL，性能无影响拿到ORM带参数使用的SQL

                new SoftwareException($"数据库异常，sql语句：{exp.Sql}", exp);
            };
        }

        /// <summary>
        /// 获取DB，保证唯一性
        /// </summary>
        /// <returns></returns>
        public object GetDb()
        {
            return _dbContext.DB;
        }

        public SqlSugarClient GetDbClient()
        {
            return _dbContext.DB;
        }

        public void OpenDB()
        {
            _dbContext.DB.Open();
        }

        public void CloseDB()
        {
            _dbContext.DB.Close();
        }

        public void InitDB()
        {
            _dbContext.DB.CodeFirst.InitTablesWithAttr(typeof(Table_His),
                typeof(Table_bacteria),
                typeof(Table_medicine),
                typeof(Table_SIR),
                typeof(Table_MonitorMes),
                typeof(Table_ResultReported));
            //_dbContext.DB.CodeFirst.InitTables(typeof(CalRegister), typeof(CalResult), typeof(CalResultPoint),
            //    typeof(CalTestRegister), typeof(Patient), typeof(Project), typeof(ProjectGroup), typeof(QCRegister),
            //    typeof(QCResult), typeof(QCTestRegister), typeof(Reagent), typeof(Consumable), typeof(Sample), typeof(SampleResult),
            //    typeof(SampleTest), typeof(SampleTestResult));
            //BaseDBConfig.DB.CodeFirst.InitTables(typeof(QCTotal));
        }

        public void DropDB(string table)
        {
            if(table== "TB_SIR")
            {
                _dbContext.DB.DbMaintenance.DropTable(typeof(Table_SIR));
                _dbContext.DB.CodeFirst.InitTablesWithAttr(typeof(Table_SIR));
            }
            else if (table == "TB_bacteria")
            {
                _dbContext.DB.DbMaintenance.DropTable(typeof(Table_bacteria));
                _dbContext.DB.CodeFirst.InitTablesWithAttr(typeof(Table_bacteria));
            }
            else if (table == "TB_medicine")
            {
                _dbContext.DB.DbMaintenance.DropTable(typeof(Table_medicine));
                _dbContext.DB.CodeFirst.InitTablesWithAttr(typeof(Table_medicine));
            }
        }

        public void BeginTran()
        {
            lock (this)
            {
                TranCount++;
                GetDbClient().BeginTran();
            }
        }

        public void CommitTran()
        {
            lock (this)
            {
                TranCount--;
                if (TranCount == 0)
                {
                    try
                    {
                        GetDbClient().CommitTran();
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.Message);
                        GetDbClient().RollbackTran();
                    }
                }
            }
        }

        public void RollbackTran()
        {
            lock (this)
            {
                TranCount--;
                GetDbClient().RollbackTran();
            }
        }
    }
}
